﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.SignalR.Client;
using System.Threading.Channels;
using Zocono.Infrastructure.SignalR.Models;
using System.ComponentModel;
using System.Reflection;
using Newtonsoft.Json;

namespace Zocono.Infrastructure.SignalR
{
    public class SignalRClient
    {
        HubConnection connection1;

        public SignalRClient()
        {
            connection1 = GetConnection("MENGMENG");
            var unused = InitAsync();
        }

        public async Task InitAsync()
        {
            await connection1.StartAsync();
            _ = RelateService();
        }
        //关联服务端
        public async Task RelateService()
        {
            //指定用户发送
            await connection1.SendAsync("SendToClient", connection1.ConnectionId);
        }
        static HubConnection GetConnection(string name)
        {
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:44371/equipmentSignalRService").Build();
            //断线重连
            connection.Closed += async (sender) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await connection.StartAsync();
            };

            //注册服务端响应
            connection.On<string>("CallByHub", (str) =>
            {
                var type = JsonConvert.DeserializeObject<List<ProcessModule>>(str);
            });
            return connection;
        }
    }
}
